// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Dashboard from '../views/Dashboard.vue';
import Layout from "@/components/Layout/Layout.vue";
import CourseList from "@/views/course/CourseList.vue";
import Login from "@/views/login/Login.vue";
import {useUserStore} from "@/stores/user.js";
import PublishHomework from "@/views/homework/PublishHomework.vue";
import StudentList from "@/views/student/StudentList.vue";
import HomeworkManagement from "@/views/homework/HomeworkManagement.vue";
import StudentPerformance from "@/views/student/StudentPerformance.vue";
import AddCourse from "@/views/course/AddCourse.vue";
import CourseComment from "@/views/course/CourseComment.vue";
import ListBlogs from "@/views/blog/ListBlogs.vue";
import PublishBlogs from "@/views/blog/PublishBlogs.vue";
import ChapterList from "@/views/course/ChapterList.vue";


const routes = [
  {
    path: '/',
    name: 'appLayout',
    component: Layout,
    redirect: '/dashboard',
    children:[
      {
        name: 'dashboard',
        path: '/dashboard',
        component: Dashboard
      },
      { path: '/course-list', name: 'course-list', component: CourseList },
      {path: '/add-course', name: 'add-course', component: AddCourse},
      {path: '/course-comment', name: 'course-comment', component: CourseComment},

       { path: '/publish-homework', name: 'publish-homework', component: PublishHomework },
       { path: '/homework-management', name: 'homework-management', component: HomeworkManagement },

       { path: '/student-list', name: 'student-list', component: StudentList },
       { path: '/student-performance', name: 'student-performance', component: StudentPerformance },

      {path: '/list-blogs',name: 'list-blogs',component: ListBlogs},
      {path: '/publish-blogs',name: 'publish-blogs',component: PublishBlogs},
      // { path: '/profile-settings', name: 'profile-settings', component: ProfileSettings },
       // { path: '/system-settings', name: 'system-settings', component: SystemSettings },
      {path: '/chapter-list/:courseId',name: 'chapter-list',component: ChapterList}
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  }

];



const router = createRouter({
  history: createWebHistory(),
  routes,
});

const whiteList = ['/login']; // 定义白名单
// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to：跳转的路由对象
  // from：从哪里来
  // next：放行next() 重定向next(路径)
  const authStore = useUserStore(); // 获取 authStore 实例
  const hasToken = !!authStore.getToken(); // 检查是否有 token
  if (hasToken) {
    // 如果有 token
    if (to.path === '/login') {
      // 如果目标路由是登录页面，重定向到首页
      next('/');
    } else {
      // 如果不是登录页面，允许访问
      next();
    }
  } else {
    console.log("没有 token",hasToken)
    // 如果没有 token
    if (whiteList.includes(to.path)) {
      // 如果目标路由在白名单中，允许访问
      next();
    } else {
      // 如果目标路由不在白名单中，重定向到登录页面
      next('/login');
    }
  }
});

export default router;
